package service.api.ai;

import com.alibaba.fastjson.JSONObject;
import entity.AccessToken;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import redis.JedisConnectPool;
import redis.clients.jedis.Jedis;
import service.WxServiceImpl;
import util.Request;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
public class ERNIE_ViLG {
    static InputStream in = ERNIE_ViLG.class.getClassLoader().getResourceAsStream("wx-config.xml");
    static Map<String, String> Xmlmap = WxServiceImpl.parseRequest(in);
    private static final String ERNIEAPI = Xmlmap.get("ERNIEAPI");
    private static final String ERNIESecret = Xmlmap.get("ERNIESecret");
    private static final String ERNIETokenUrl = Xmlmap.get("ERNIETokenUrl");
    private static final String ERNIETaskUrl = Xmlmap.get("ERNIETaskUrl");
    private static final String ERNIEGetImg = Xmlmap.get("ERNIEGetImg");
    private static AccessToken at;
    private static final JedisConnectPool jedisConnectPool = new JedisConnectPool();
    private static Jedis jedis=jedisConnectPool.getJedis();

    public String clickMenu(String openId) {
        jedis.set(openId, "wait");
        jedis.expire(openId,61);
        long wait = jedis.scard("openId_set");
        return "当前排队人数：" + wait + "\r\n预计等待时间：" + (wait * 35 + 35) + "秒\r\n请在1分钟内描述图片，如想取消请回复“取消”\n48小时内最多可使用20次";
    }

    private void getToken() {
        String url = ERNIETokenUrl.replace("{your_ak}", ERNIEAPI).replace("{your_sk}", ERNIESecret);
        String tokenStr = Request.sendPostERNIE(url, null);
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        String token = jsonObject.getString("data");
        at = new AccessToken(token, 86400);
    }

    private String getTokenByIsExpires() {
        if (at == null || at.isExpires()) {
            getToken();
        }
        return at.getToken();
    }

    public String getTaskId(String text) {
        String Token = getTokenByIsExpires();
        String url = ERNIETaskUrl.replace("{access_token}", Token);
//        String data= "{\"text\":\"" +text+ "\",\"style\":\"油画\"}";
//        String res= API.sendPostERNIE(url,null);
//        return String.valueOf(JSONObject.parseObject(res).getJSONObject("data").getIntValue("taskId"));
        try {
            PostMethod postMethod = new PostMethod(url);
            //添加请求头数据
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            //参数设置，需要注意的就是里边不能传NULL，要传空字符串
            NameValuePair[] data = {
                    new NameValuePair("text", text),
                    new NameValuePair("style", "油画")
            };

            postMethod.setRequestBody(data);

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String res = postMethod.getResponseBodyAsString();
            log.info("getTask  :"+res);
            return String.valueOf(JSONObject.parseObject(res).getJSONObject("data").getIntValue("taskId"));
        } catch (Exception e) {
             log.info("请求异常"+e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private JSONObject waitImg(String taskId) {
        String Token = getTokenByIsExpires();
        String url = ERNIEGetImg.replace("{access_token}", Token);
        try {
            PostMethod postMethod = new PostMethod(url);
            //添加请求头数据
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            //参数设置，需要注意的就是里边不能传NULL，要传空字符串
            NameValuePair[] data = {
                    new NameValuePair("taskId", taskId),
            };

            postMethod.setRequestBody(data);

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String res = postMethod.getResponseBodyAsString();

            JSONObject jsonObject = JSONObject.parseObject(res);
            return jsonObject;
        } catch (Exception e) {
            // logger.info("请求异常"+e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public Set<String> getImg(String taskId) {
        Set<String> images = new HashSet<>();
        JSONObject jsonObject = waitImg(taskId);
        log.info("getImg  :"+jsonObject.toString());
        JSONObject dataJSON = jsonObject.getJSONObject("data");
        String wait = dataJSON.getString("waiting");
        if (wait.equals("0")) {
            images.add(dataJSON.getString("img"));
//            for (int i = 0; i < 10; i++) {
//                images.add(dataJSON.getJSONArray("imgUrls").getJSONObject(i).getString("image"));
//            }
        } else {
            try {
                Thread.sleep(1000);

                while (true) {
                    jsonObject = waitImg(taskId);
                    log.info("getImg  :"+jsonObject.toString());
                    dataJSON = jsonObject.getJSONObject("data");
                    wait = dataJSON.getString("waiting");
                    if (wait.equals("0")) {
                        images.add(dataJSON.getString("img"));
//                        for (int i = 0; i < 10; i++) {
//                            images.add(dataJSON.getJSONArray("imgUrls").getJSONObject(i).getString("image"));
//                        }
                        break;
                    }else
                        Thread.sleep(Long.parseLong(wait.substring(0,wait.length()-1)) * 1000);

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return images;
    }


}
